package com.bestv.search.engine.servlet;

import com.bestv.search.common.util.StringConst;
import com.bestv.search.engine.command.LuceneSearchCommandRefactor;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Document;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author Justin Luo
 */

// $Id: PersonServlet.java 23 2013-09-12 06:30:55Z Justin $
public class PersonServlet extends HttpServlet {

    private static final long serialVersionUID = 812773131623416456L;
    protected static SimpleDateFormat timeformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    protected final Log log = LogFactory.getLog(getClass());

    public PersonServlet() {
        super();
    }

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        try {
            String schCon = URLDecoder.decode(request.getParameter("q"), "UTF-8");
            log.info(timeformat.format(new Date()) + "|" + request.getRemoteAddr() + "|" + schCon);
            String avatarRoot = request.getRequestURL().toString();
            // change to Avatar folder
            avatarRoot = avatarRoot.replace("/doperson", "/avatar/");
            doExecute(schCon, response, avatarRoot);
        } catch (Exception e) {
            response.getWriter().write("Parameter Error,please send param 'q'");
        }
    }

    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        log.debug("doPost");
        try {
            response.setContentType("text/html;charset=UTF-8");
            String schCon = URLDecoder.decode(request.getParameter("q"), "UTF-8");
            log.info(timeformat.format(new Date()) + "|" + request.getRemoteAddr() + "|" + schCon);
            String avatarRoot = request.getRequestURL().toString();
            // change to Avatar folder
            avatarRoot = avatarRoot.replace("/doperson", "/avatar/");
            doExecute(schCon, response, avatarRoot);
        } catch (Exception e) {
            response.getWriter().write("Parameter Error,please post param 'q'");
        }
    }

    @Override
    public void init() throws ServletException {
        super.init();
    }

    public void doExecute(String schCon, HttpServletResponse response, String avatarRoot) throws IOException {
        schCon = new String(schCon.getBytes("iso-8859-1"), "utf-8");
        log.info("schCon:" + schCon);
        SAXReader reader = new SAXReader();
        Document doc = null;
        InputStream xmlInputStream = new ByteArrayInputStream(schCon.getBytes("UTF-8"));
        try {
            doc = reader.read(xmlInputStream);
        } catch (Exception e) {
            response.getWriter().write("Error!The Request Parameter cannot parse to XML");
            return;
        } finally {
            xmlInputStream.close();
        }
        String cmd = doc.selectSingleNode("/request/cmd").getText();
        if (cmd != null && cmd.equalsIgnoreCase(StringConst.GETPERSONAIL)) {
            String personId = doc.selectSingleNode("/request/personId").getText();
            if (personId == null || personId.equals(StringConst.EMPTY)) {
                log.error(" Invalid request from personId " + personId);
                response.getWriter().write("<record></record>");
            } else {
                // 0: return all products(include online and off line) that
                // related with this person, default value is 0
                // 1: return all products(online product) that related with this
                // person,
                // other: don't return any products(include online and off line)
                // that related with this person
                int productFlag = 0;
                Node product = doc.selectSingleNode("/request/productFlag");
                if (product != null) {
                    try {
                        productFlag = Integer.valueOf(product.getText().trim());
                    } catch (Exception e) {
                        log.warn("Invalid product flag " + product.getText());
                        productFlag = 0;
                    }
                }

                String result = LuceneSearchCommandRefactor.getPersonDetailsById(personId, avatarRoot, productFlag);
                if (result == null || personId.equals(StringConst.EMPTY)) {
                    response.getWriter().write("<record></record>");
                    log.warn("Don't find any person " + schCon);
                } else {
                    log.info("Results:" + result);
                    response.getWriter().write(result);
                }
            }
        } else {
            log.error(" Invalid request from cmd " + cmd);
            response.getWriter().write("<record></record>");
        }
    }
}
